<script setup lang="ts">
import {ref, computed, watch} from 'vue';
import {message} from 'ant-design-vue';
import dayjs from 'dayjs';
import {PlusSquareOutlined, ExclamationCircleOutlined} from '@ant-design/icons-vue';
import {VxeTableInstanceType, VxeTableRowType} from './types';

const props = withDefaults(defineProps<{visible: boolean}>(), {
  visible: false,
});
const tableRef = ref<VxeTableInstanceType>();
const initTableColumns: VxeTableRowType[] = [
  {
    sortVal: dayjs().valueOf(),
    deadlineTime: undefined, // 截单时间
    condition: 1, // 截单条件
    additionalType: '', // 截单附加条件类型
    calculationRuleDay: 1, // 2400计算规则天
  },
];

const tableColumns = ref<VxeTableRowType[]>(initTableColumns); // 表格数据
const options = ref([
  {label: '请选择', value: '', other: true, disabled: false}, // 请选择
  {label: '与中心签出同一天', value: 1, disabled: false}, // 与中心签出同一天
  {label: '与中心签出跨天', value: 2, disabled: false}, // 与中心签出跨天
]);
const tempTableList: any = ref(); // 临时存放的 Table数据
const symbolOptions = ref([
  {label: '>', value: 1},
  {label: '≥', value: 2},
  {label: '<', value: 3},
  {label: '≤', value: 4},
]);
// 验证规则 函数 -start
const checkRules = computed(() => {
  return (item: any) => {
    return !item.deadlineTime || !item.calculationRuleDay;
  };
});
const checkRulesOpacity = computed(() => {
  return (value: any) => {
    return !value ? 1 : 0;
  };
});
const checkRulesRedLine = computed(() => {
  return (value: any) => {
    return !value ? 'red' : null;
  };
});
// 验证规则 函数 -end
// 新增
const insertEvent = async (row?: VxeTableRowType | number) => {
  const $table = tableRef.value;
  if ($table) {
    if ($table?.getTableData().tableData && $table?.getTableData().tableData.length >= 3) {
      return;
    }
    const record = {
      sortVal: dayjs().valueOf(), //
      deadlineTime: undefined, // 截单时间
      condition: 1, // 截单条件
      additionalType: '', // 截单附加条件类型
      calculationRuleDay: 1, // 2400计算规则天
    };
    const {row: newRow} = await $table.insertAt(record, row);
    // console.log('tableData', $table?.getTableData().tableData);
    await $table.setEditCell(newRow, 'name');
    tempTableList.value = $table?.getTableData().tableData;
  }
};
// 删除
const removeEvent = async (row: VxeTableRowType) => {
  const $table = tableRef.value;
  if ($table) {
    if ($table?.getTableData().tableData && $table?.getTableData().tableData.length <= 1) {
      return message.error('不能删除 必须保留一条数据');
    }
    await $table.remove(row);
    console.log('row', row);
    tempTableList.value = $table?.getTableData().tableData;
    options.value.forEach((item) => {
      if (item.value == row.additionalType) {
        item.disabled = false;
      }
    });
  }
};
// 选择
const handleChange = () => {
  options.value.forEach((item) => {
    item.disabled = false;
    tempTableList.value?.forEach((i: any) => {
      if (item.other) {
        item.disabled = false;
      } else if (i.additionalType == item.value) {
        item.disabled = true;
      }
    });
  });
};
watch(
  () => props.visible,
  (nextState) => {
    if (!nextState) {
      console.log('触发');
      tableColumns.value = [...initTableColumns];
    }
  },
);
// vue3 新增-导出 父组件ref 调用
defineExpose({tableRef});
</script>
<template>
  <div class="z-dynamic-table">
    <vxe-table
      ref="tableRef"
      border
      show-overflow
      keep-source
      max-height="400"
      :data="tableColumns"
      :edit-config="{trigger: 'click', mode: 'cell', showStatus: false}"
    >
      <vxe-column field="deadlineTime" title="截单时间" width="200" show-overflow>
        <template #header>
          <div class="z-flex-center">
            <span style="margin-right: 2px; color: red">*</span>
            <div>截单时间</div>
            <a-tooltip placement="top">
              <template #title>
                <span>提示一下</span>
              </template>
              <ExclamationCircleOutlined class="pointer" style="margin: 0 0 0 5px; font-size: 15px" />
            </a-tooltip>
          </div>
        </template>
        <template #default="{row}">
          <div style="width: 100%">
            <span>T</span>
            <a-select
              v-model:value="row.condition"
              :options="symbolOptions"
              style="margin-right: 5px; margin-left: 10px; width: 60px"
            >
            </a-select>
            <a-time-picker
              v-model:value="row.deadlineTime"
              :allow-clear="false"
              placeholder=""
              :style="{width: '100px', borderColor: checkRulesRedLine(row.deadlineTime)}"
            />
            <div v-show="checkRules(row)" :style="{color: 'red', opacity: checkRulesOpacity(row.deadlineTime)}">
              不能为空
            </div>
          </div>
        </template>
      </vxe-column>
      <vxe-column field="additionalType" title="截单附加条件" show-overflow>
        <template #default="{row}">
          <a-select v-model:value="row.additionalType" :options="options" style="width: 100%" @change="handleChange" />
          <div v-show="checkRules(row)" style="color: red; opacity: 0">不能为空</div>
        </template>
      </vxe-column>
      <vxe-column field="calculationRuleDay" title="2400计算规则" show-overflow>
        <template #header>
          <div class="z-flex-center">
            <span style="margin-right: 2px; color: red">*</span>
            <div>2400计算规则</div>
            <a-tooltip placement="top">
              <template #title>
                <span>提示一下</span>
              </template>
              <ExclamationCircleOutlined class="pointer" style="margin: 0 0 0 5px; font-size: 15px" />
            </a-tooltip>
          </div>
        </template>
        <template #default="{row}">
          <div style="width: 100%">
            <div style="display: flex; justify-content: center; align-items: center">
              <span style="display: inline-block"> 2400 = T + </span>
              <a-input-number
                id="inputNumber"
                v-model:value="row.calculationRuleDay"
                :controls="false"
                :min="1"
                :max="99"
                :style="{width: '60px', borderColor: checkRulesRedLine(row.calculationRuleDay)}"
              ></a-input-number>
            </div>
            <div v-show="checkRules(row)" :style="{color: 'red', opacity: checkRulesOpacity(row.calculationRuleDay)}">
              不能为空
            </div>
          </div>
        </template>
      </vxe-column>
      <vxe-column title="删除" width="100">
        <template #default="{row}">
          <a-popconfirm title="删除" placement="left" @confirm="removeEvent(row)">
            <span style="cursor: pointer" class="delete-icon"> 删除 </span>
          </a-popconfirm>
        </template>
      </vxe-column>
    </vxe-table>
    <a-row justify="center">
      <a-button type="primary" class="add-button-view" @click="insertEvent(-1)">
        <PlusSquareOutlined style="margin-top: 2px; font-size: 18px" />
        <span style="font-size: 14px">新增</span>
      </a-button>
    </a-row>
  </div>
</template>

<style lang="less" scoped>
.z-dynamic-table {
  .add-button-view {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0 50px;
    margin-top: 20px;
  }

  .delete-icon {
    color: #555;

    &:hover {
      color: red;
    }
  }

  .z-flex-center {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  :deep(.vxe-table) {
    .vxe-body--column {
      padding: 10px 0 !important;
      height: auto !important;
    }

    .c--tooltip {
      max-height: auto !important;
    }

    .vxe-body--row {
      height: unset !important;
    }
    // .ant-select-selection-item {
    //   color: #bfbfbf !important;
    // }
  }

  :deep(.vxe-body--column.col--ellipsis) {
    .vxe-cell {
      max-height: unset !important;
    }
  }

  :deep(.vxe-footer--column.col--ellipsis) {
    .vxe-cell {
      max-height: unset !important;
    }
  }

  :deep(.vxe-header--column.col--ellipsis) {
    .vxe-cell {
      max-height: unset !important;
    }
  }
}
</style>
